package com.example.study.component;

import com.example.study.dao.User;
import com.example.study.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;

/**
 * 监听Servlet上下文，将数据放在缓存中，减少数据库的压力
 */
@Component
public class MyServletContextListener implements ApplicationListener<ContextRefreshedEvent> {




    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //首先获取上下文
        ApplicationContext applicationContext = event.getApplicationContext();
        //获取对应的Service
        UserService userService = applicationContext.getBean(UserService.class);
        User user = userService.getAll();
        // 获取application域对象，将查到的信息放到application域中
        ServletContext application = applicationContext.getBean(ServletContext.class);
        application.setAttribute("user", user);
    }
}
